<template>
  <!-- 需求初审 -->
  <div class="container">
    <el-row class="">
      <el-col :span="16" align="left">
        <el-input v-model="data.params.projectName" placeholder="项目名称" style="width: 150px; margin-right: 15px" />
        <el-button color="#626aef" @click="search()" class="ordinary">搜索</el-button>
      </el-col>

      <el-col :span="8" align="right">
<!--        <el-button class="ordinary" @click="getExport()" v-limit="'XMZX:SZXMLXPS:XQCS:EXPORT'">批量导出</el-button>-->
        <el-button class="ordinary" @click="handleExport()" v-limit="'XMZX:SZXMLXPS:XQSQ:EXPORT'"> 批量导出</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'XMZX:SZXMLXPS:XQCS:REPREREV'">需求初审</el-button>
      </el-col>
    </el-row>

    <div>
      <!-- <Table class="table_" :tableArr="data.allTableData" :pagination="data.page" :columns="data.columns" @delectTable="delectIds" @selectTable="selectTable"
        :total="data.page.total">
        <template #operate="{ row }">
          <el-button size="small" class="ordinary" :disabled="row.isLock == 1" @click="handleEdit(row)">详情</el-button>
        </template>
      </Table> -->
      <el-table :data="data.allTableData" style="width: 100%" class="center-table"
        :cell-style="tableCellStyle"    @row-dblclick="handleRowClick" >
        <el-table-column width="55" align="center" prop="checked" label="选择">
          <template #default="{row,$index}">
                <el-checkbox v-model="row.checked" @change="selectTable( $event, row , $index)" ></el-checkbox>
            </template>
        </el-table-column>
        <el-table-column type="index" :index="indexMethod" label="序号" width="50" />
        <ColumnData v-for="column of data.columns" :key="column.label" :item="column" />
        <el-table-column  label="操作" width="200" fixed="right">
          <template #default="row">
            <el-button size="small" class="ordinary" :disabled="row.isLock == 1" @click="handleEdit(row)" v-limit="'XMZX:SZXMLXPS:XQCS:DETAILS'">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="example-pagination-block">
            <el-pagination
              :current-page="data.params.current"
              :page-size="data.params.size"
              :page-sizes="[10, 20, 30, 40,50,100]"
              background
              layout="prev, pager, next ,total,sizes,jumper"
              :total="data.page.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
      </div>
    </div>

    <!-- 审批弹窗 -->
    <el-dialog v-model="data.dialogVisible" width="60%" :show-close="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="first">
              <el-form v-model="form" :rules="rules" ref="needDeptSuggest" status-icon label-position="right" label-width="120px"
                :inline="true" class="demo-form-inline">
                <el-form-item label="审查意见" style="width: 100%" prop="needDeptSuggest">
                  <el-input v-model="form.needDeptSuggest"  maxlength="512" type="textarea" placeholder="请输入" />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <!-- <el-tab-pane label="相关附件" name="third">
              <platformFiles :files="data.files" @dataChange="dataChange" @filesParams="filesParams"></platformFiles>
            </el-tab-pane> -->
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary"  @click="examine()">初审通过</el-button>
          <el-button @click="unexamine()">初审不通过</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog v-model="data.detailDialog" width="60%" :show-close="false">
      <template #title>
        <div class="my-header">
          <el-tabs class="demo-tabs" v-model="activeName">
            <el-tab-pane label="详情" name="first">
              <el-form :model="data.detailForm" status-icon label-position="right" label-width="120px"
                :inline="true" class="demo-form-inline">
                <el-form-item label="项目名称" >
                  <el-input v-model="data.detailForm.projectName"  placeholder="请输入" :disabled="true" />
                </el-form-item>
                <el-form-item label="申报部门/单位">
                  <el-input v-model="data.detailForm.applyUnitName"  placeholder="请输入" :disabled="true"/>
                </el-form-item>
                <el-form-item label="建设预算(万元)">
                  <el-input v-model="data.detailForm.buildBudget"   placeholder="请输入" :disabled="true"/>
                </el-form-item>
                <el-form-item label="申请日期" >
                  <el-input v-model="data.detailForm.applyDatetime" placeholder="请输入" :disabled="true"/>
                </el-form-item>
                <el-form-item label="建设目标"  style="width: 100%;">
                  <el-input v-model="data.detailForm.buildTarget" :disabled="true" :autosize="{ minRows: 2 }" maxlength="300" type="textarea" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="建设内容" style="width: 100%">
                  <el-input v-model="data.detailForm.buildContent" :disabled="true" :autosize="{ minRows: 2 }" maxlength="300" type="textarea"
                    placeholder="请输入" />
                </el-form-item>
                <el-form-item label="需求部门意见" style="width: 100%">
                  <el-input v-model="data.detailForm.needDeptSuggest" :disabled="true" :autosize="{ minRows: 2 }" maxlength="300" type="textarea"
                    placeholder="请输入" />
                </el-form-item>
                <el-form-item label="状态" >
                  <el-input v-model="data.detailForm.status" :disabled="true" placeholder="请输入" />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="third" >
              <platformFiles :files="data.files"  @filesParams="filesParams" :filesTypeFlag="false" :isExamine="true"
                             download="XMZX:SZXMLXPS:XQSQ:DOWNLOAD"  upload="XMZX:SZXMLXPS:XQSQ:UPLOAD" fileDelete="XMZX:SZXMLXPS:XQSQ:FILEDELETE"
              ></platformFiles>
            </el-tab-pane>
            <el-tab-pane v-if="data.approvalFormalExamination.auditPeopleName" label="审批详情" name="approvalInfo">
              <el-form class="inline-form" label-position="top" status-icon label-width="140px">
                <el-form-item label="审查结果："> {{data.approvalFormalExamination.status_text}} </el-form-item>
                <el-form-item label="审查人：">  {{data.approvalFormalExamination.auditPeopleName}} </el-form-item>
                <el-form-item label="审查时间："> {{data.approvalFormalExamination.applyDatetime}} </el-form-item>
                <el-form-item label="审查意见：">
                  <el-input type="textarea" disabled v-model="data.approvalFormalExamination.auditSuggest"></el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary"  @click="data.detailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 导出字段选择 -->
    <Export
        :detailList="data.detailList"
        :showing="data.exportDialog"
        @close="closeExport"
        @handle-filed="handleFiled"
    ></Export>
  </div>
</template>
<script lang="ts">
import Information from '@/views/project/digit/requirementApplication/information.vue'
import {
  examineTable,
  getDetail,
  getExportFirst, getExportFirst1,
  getExportInnovativeTalentTeam1,
  getInnova, getInnovativeTalentTeamDetail,
  getAuditSuggest,
  getList,
  unexamineTable
} from '@/views/science/api/digit'
import Members from '@/views/science/components/members/members.vue'
import platformFiles from '@/views/science/components/platformFiles/platformFilesxq.vue'
import record from '@/views/science/components/record/record.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import ColumnData from '@/views/science/components/table/column-data.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals, tips } from '@/views/science/components/tips/tips'
import {ElMessage, ElMessageBox, UploadProps} from "element-plus"
import { computed, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import tableData from './tableHeader.json'
import Export from '@/views/project/components/Export/index.vue'
export default {
  components: {
    SelectOption,
    Table,
    Information,
    Members,
    platformFiles,
    record,
    ColumnData,
    Export
  },
  setup() {
    const store = useStore()
    const activeName = ref('first')
    const pagination = reactive({  //分页器信息
      pageSize:10,
      currentPage:1,
    })
    //分页操作
    const handleSizeChange = (val) =>{
      data.params.current = 1
      data.params.size = val
      tableList()
    }
    const handleCurrentChange = (val) =>{
      data.params.current = val
      tableList()
    }
    //弹框
    const form = reactive({
      needDeptSuggest:'',
    })
    const rules = reactive({
      needDeptSuggest: [
        { required: true, message: '请输入审查意见', trigger: 'blur' },
      ],
    })

    let data = reactive({
      detailId:'',
      dialogVisible: false,
      addFlag: 0,
      recordShow: false,
      loading: false,
      page: { page: 1, limit: 10, total: 4 },
      params: {
        projectName : '',
        current: 1,
        size: 10,
      },
      selectedRows: [],
      columns: tableData.platformTableHeader,
      ids: [],
      allTableData: [],
      orgAllList: computed(() => store.state.technologyStrength.orgAllList),
      levelOptions: computed(() => store.state.innovativeTalents.cxlevelSelect),
      members: [],
      files: [],
      changeLogs: [],
      flag: null,

      baseInfo: [],
      memberList: [],
      fileList: [],
      tableItem:{id:'',},//当前选中的行
      //详情
      detailDialog:false,
      detailForm:{
        projectName:'',
        applyUnitName:'',
        buildTarget:'',
        buildBudget:'',
        needDeptSuggest:'',
        applyDatetime:'',
        status:'',
        buildContent:'',
      },
      exportDialog: false,
      detailList: [] as any,
      approvalFormalExamination: {
        auditPeopleName: '',
        auditSuggest: '',
        applyDatetime: '',
        status_text: '',
      }
    });
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      // let sdt = selectArr.map((el) => el.id);
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          // exportProjectList({ ...searchParams, ids: sdt.join(",") , headList: arr }, '科研项目数据表格')
          getExportFirst1({ ...data.params, ids: [data.tableItem.id] , headList: arr}, "需求初审");
          console.log('批量导出')
          data.exportDialog = false;


        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'applyUnitName', title: '申报单位' },
        { fieldName: 'buildBudget', title: '建设预算 (万元)' },
        { fieldName: 'buildContent', title: '建设内容' },
        { fieldName: 'buildTarget', title: '建设目标' },
        { fieldName: 'needDeptSuggest', title: '需求部门意见' },
        /*        { fieldName: 'applyPeople', title: '申请人' },
                { fieldName: 'applyPeopleName', title: '申请人姓名' },
                { fieldName: 'researchcontents', title: '主要研究内容' },
                { fieldName: 'mainindicators', title: '主要技术经济指标' },
                { fieldName: 'describetwo', title: '创新点及可能获得的成果和知识产权' },
                { fieldName: 'backdrop', title: '立项背景' },
                { fieldName: 'analysis', title: '国内外研究概况及可行性分析' },
                { fieldName: 'qualification', title: '项目研究的主要内容及技术指标' },
                { fieldName: 'roadmap', title: '项目研究的技术路线' },
                { fieldName: 'forecast', title: '推广应用前景及经济效益预测' },
                { fieldName: 'dividethework', title: '申报单位和协作单位及分工' },
                { fieldName: 'programme', title: '项目进度计划' },*/
      ]
    }
    interface Config {
      id: string;
    }
    let selectArr: Config[] = reactive([]);
    const handleSelectionChange = (val) => {
      selectArr = val;
    };

    const value = ref('2021-10-29')
    const holidays = [
      '2021-10-01',
      '2021-10-02',
      '2021-10-03',
      '2021-10-04',
      '2021-10-05',
      '2021-10-06',
      '2021-10-07',
    ]

    const isHoliday = ({ dayjs }) => {
      return holidays.includes(dayjs.format('YYYY-MM-DD'))
    }

    //主页面表格初始化
    const tableList = async () => {
      let res = await getList(data.params)
      if (res.data.success) {
        let records = res.data.data
        records.records.map((item) => {
          // if (item.status == 0) {
          //   item.status = "待确认"
          // } else {
          //   item.status = "已确认"
          // }
          if (item.status == 1) {
            item.status = "待审批"
          } else if (item.status == 2) {
            item.status = "审批通过"
          }else if (item.status == 3) {
            item.status = "审批未通过"
          }
        })
        //给数据添加checked属性并默认置为false
        for ( let index in res.data.data.records ){
            res.data.data.records[index].checked = false
        }
        data.allTableData = res.data.data.records
        data.page.total = records.total
      }
    }

    let detailForm = reactive({})
    //详情数据获取
    const detailData = async (id) => {
      console.log('id',id);
      let res = await getInnovativeTalentTeamDetail(id)
      if (res.data) {
        store.commit('innovativeTalents/getTalentTeamInfo', { ...res.data.data })
        detailForm = res.data.data
        data.files = res.data.data.needAttachment || []
        console.log('详情数据获取',detailForm);
      }
    }
    const indexMethod = (index)=>{
      return data.params.size*(data.params.current-1) +index+1
    }
    const delectIds = (ids) => {
      console.log('ids',ids[ids.length - 1]);
      data.ids = ids
    }
    //单选
    const selectTable = (e,row,index) =>{
      const data1 = data.allTableData
      //遍历表格的数据，将非本行的所有数据的checked属性置为false，即取消选择
      for(let i in data1){
          if( i == index ){
              (data1[i] as any).checked = e
          }else{
              (data1[i] as any).checked = false
          }
      }
      data.allTableData = data1
      if(e){
        data.tableItem = row
      }else{
        data.tableItem = {id:''}
      }
      // console.log('data.tableItem',data.tableItem,Object.keys(data.tableItem).length);
    }

    const valueFlag = (flag) => {
      data.flag = flag
    }

    const paramsChange = (params) => {
      data.memberList = params
    }


    const filesParams = (params) => {
      data.fileList = params
    }

    const getExport = async () => {
      console.log('getExport',data.params.projectName);
      Modals('是否导出全部数据', '提示', 'warning').then(async () => {
        await getExportFirst({projectName:data.params.projectName})
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      data.page.page = 1
      tableList()
    }

    //需求初审
    const handleAdd = () => {
      if(Object.keys(data.tableItem).length > 1){
        data.dialogVisible = true
      }else{
        ElMessage.warning(`请选择要初审的内容`)
      }
    }
    const handleRowClick = (row) => {
      handleEdit({ row })
    }

    const handleEdit = (row) => {
      activeName.value = "first";
      getAuditSuggest({id: row.row.id}).then(res => {
        console.log(res)
        if(res.data.success) {
          data.approvalFormalExamination = res.data.data
        }
      })
      data.detailForm = Object.assign({},row.row)
      data.detailId = row.id
      detailData({id:row.row.id})
      data.detailDialog = true
      // data.detailId = row.id
      // detailData({id:row.id})
      // data.dialogVisible = true
      data.addFlag = 1
      store.commit('innovativeTalents/getRowId', row.id)
    }

    const handleConfirm = async (row) => {
      Modals('是否确认当前流程', '提示', 'warning').then(async () => {
        let res = await getInnova(row.id)
        if (res.data.success) {
          console.log(res)
          tableList()
        }
      }).catch(() => {
        console.log("点击了取消")
      })

    }

    const getAssociation = ref()
    const handleSave = async () => {
      const form = store.state.innovativeTalents.talentTeamInfo

      if (!data.flag) {
        return
      }
      const params = {
        projectName: form.projectName,
        applyUnit: form.applyUnit,
        buildBudget: form.buildBudget,
        buildContent: form.buildContent,
        buildTarget: form.buildTarget,
        needDeptSuggest: form.needDeptSuggest,
        needAttachment:[
          { fileId: "f6dcc4168ca428ee4c48cb3d8041cc9b",
            fileName:"接口问题.txt",
            path:"http://101.34.142.46:8099/group1/M00/00/01/ZSKOLmT-z7GAerNVAAABI42Nt2g160.txt",
            type: "txt"}
          ],//data.files
      }
      let res
      if (data.addFlag == 0) {
        // res = await getAddInnovativeTalentTeam(params)
      } else {
        const paramss = {
          id:data.detailId,
          projectName: form.projectName,
          applyUnit: form.applyUnit,
          buildBudget: form.buildBudget,
          buildContent: form.buildContent,
          buildTarget: form.buildTarget,
          needDeptSuggest: form.needDeptSuggest,
          needAttachment:[
            { fileId: "f6dcc4168ca428ee4c48cb3d8041cc9b",
              fileName:"接口问题.txt",
              path:"http://101.34.142.46:8099/group1/M00/00/01/ZSKOLmT-z7GAerNVAAABI42Nt2g160.txt",
              type: "txt"}
            ],//data.files
        }
        // res = await getUpdateInnovativeTalentTeam(paramss)
      }
      if (res.data.success) {
        console.log(res)
        data.dialogVisible = false
        activeName.value = 'first'
        tableList()
      }
    }

    //审批通过
    const examine = () => {
      console.log(data.tableItem.id,form.needDeptSuggest);
      if(form.needDeptSuggest == ''){
        tips('请输入审查意见', 'warning')
        return;
      }
      const exdata = {
        id:data.tableItem.id,
        auditSuggest:form.needDeptSuggest,
      }
      examineTable(exdata).then(res =>{
        if(res.data.code == 200){
          ElMessage.success(`审批通过`)
          tableList()
        }
      })
      data.dialogVisible = false;
    }
     //审批不通过
     const unexamine = () => {
      if(form.needDeptSuggest == ''){
        if(form.needDeptSuggest == ''){
          tips('请输入审查意见', 'warning')
          return;
        }
      }
      const exdata = {
        id:data.tableItem.id,
        auditSuggest:form.needDeptSuggest,
      }
      unexamineTable(exdata).then(res =>{
        if(res.data.code == 200){
          ElMessage.success(`审批不通过`)
          tableList()
        }
      })
      data.dialogVisible = false;
    }


    //文件上传
    const handleChange: typeof UploadProps['onChange'] = (uploadFile, uploadFiles) => {
      console.log(uploadFile, uploadFiles)
    }
    const handleSuccess: typeof UploadProps['onSuccess'] = (uploadFile,uploadFiles,fileList) => {
      if (uploadFile.code == 200) {
        tips('上传成功', 'success')
        // console.log('uploadFile',uploadFile,uploadFiles,fileList)
        data.files = fileList
        // fileList.forEach(e =>{
        //   console.log('e',e.response.data.fileId);
        // })
      } else {
        tips('上传失败', 'error')
      }
    }
    const handleError: typeof UploadProps['onError'] = (uploadFile) => {
      tips('上传失败', 'error')
    }
    const handleExceed: typeof UploadProps['onExceed'] = (files, uploadFiles) => {
      ElMessage.warning(
        `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
        } totally`
      )
    }

     // 改变某一列单元格字体颜色
     const textColorArr = computed(() => {
      const arr: any = []
      data.columns.filter((item: any, index) => {
        if (item.textColor) {
          arr.push([item.key, index])
        }
      })
      return arr
    })
     const tableCellStyle = ({ row, column, rowIndex, columnIndex }) => {
      let color
      textColorArr.value.filter((item, index) => {
        if (row[item[0]] == "待确认" && columnIndex - 2 == item[1]) {
          color = "color: #FFC783";
          return color;
        } else if (row[item[0]] == "已确认" && columnIndex - 2 == item[1]) {
          color = "color: #4bc151";
          return color;
        }
        if (row[item[0]] == "待提交" && columnIndex - 2 == item[1]) {
          color = "color: #FFC783";
          return color;
        } else if (row[item[0]] == "待审核" && columnIndex - 2 == item[1]) {
          color = "color: #FFC783";
          return color;
        }else if (row[item[0]] == "审批通过" && columnIndex - 2 == item[1]) {
          color = "color: #4bc151";
          return color;
        }else if (row[item[0]] == "审批未通过" && columnIndex - 2 == item[1]) {
          color = "color: brown";
          return color;
        }
      })
      return color
    }

    const cookie = () => localStorage.getItem('token')
    tableList()
    return {
      pagination,
      handleSizeChange,
      handleCurrentChange,
      data,
      activeName,
      valueFlag,
      getAssociation,
      paramsChange,
      filesParams,
      indexMethod,
      delectIds,
      selectTable,
      getExport,
      handleAdd,
      examine,
      unexamine,

      handleEdit,
      handleConfirm,
      search,
      handleSave,
      detailForm,
      //附件相关
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      handleExceed,
      handleChange,
      handleSuccess,
      form,
      rules,
      tableCellStyle,

      closeExport,
      handleFiled,
      handleExport,
      handleRowClick,
    }
  },
}
</script>

<style lang="scss">
.table_{
  .el-pagination {
      display: none;
    }
}
</style>
<style lang="scss" scoped>
.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}

:deep(.el-pagination .btn-prev .el-icon) {
  margin: 0 auto;
}
.container {
  background-color: white;
  padding: 20px;
}

:deep(.el-dialog__body) {
  display: none;
}

// .el-col {
//   line-height: 40px;
// }

.el-form-item {
  .el-input {
    // width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */
.dialog-footer{
  text-align: center;
}

.table {
  margin-top: 15px;
}

.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}

:deep(.el-pagination .btn-prev .el-icon) {
  margin: 0 auto;
}

:deep(.center-table td),
:deep(.center-table th) {
  text-align: center !important;
}
:deep(.center-table) {
  margin-top: 15px;
}
.demo-form-inline .el-form-item {
  width: 48%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}
.inline-form::v-deep {
  .el-form-item {
    display: flex;
  }
  .el-form-item__label {
    width: 120px;
    text-align: right;
  }
  .el-form-item__content {
    opacity: .8;
  }
}
</style>
